package crazymakercircle;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author: DRevelation
 * @Date: 2021/7/27 13:51
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws Exception {
//        CompletableFutureDemo.runAsyncDemo();
        supplyAsyncDemo();
    }

    public static void runAsyncDemo() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("run end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        future.get(2, TimeUnit.SECONDS);
    }

    public static void supplyAsyncDemo() throws Exception {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
            long start = System.currentTimeMillis();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("run end...");
            return System.currentTimeMillis() - start;
        });
        long time = future.get(2, TimeUnit.SECONDS);
        System.out.println("异步执行耗时时间（秒）= " + time / 1000);
    }
}
